import request from '@/utils/request'

// 电子围栏API

/**
 * 获取围栏列表
 * @param {Object} params 查询参数
 * @param {number} params.page 页码
 * @param {number} params.count 每页数量
 * @param {string} params.query 搜索关键词
 * @param {string} params.type 围栏类型 circle|rectangle|polygon
 * @param {string} params.status 围栏状态 active|inactive
 */
export function queryFences(params) {
  console.log('[围栏API] 请求围栏列表，参数:', params)
  
  const requestConfig = {
    method: 'get',
    url: '/api/fence/list',
    params: {
      page: params.page || 1,
      count: params.count || 10,
      query: params.query || '',
      type: params.type || '',
      status: params.status || ''
    }
  }
  
  console.log('[围栏API] 请求配置:', requestConfig)
  
  return request(requestConfig)
    .then(response => {
      console.log('[围栏API] 围栏列表响应:', response)
      return response
    })
    .catch(error => {
      console.error('[围栏API] 围栏列表请求失败:', error)
      console.error('[围栏API] 错误详情:', {
        message: error.message,
        status: error.status,
        statusText: error.statusText,
        url: error.config?.url,
        method: error.config?.method
      })
      
      // 返回模拟数据作为后备方案
      console.warn('[围栏API] 使用模拟数据作为后备方案')
      return Promise.resolve({
        code: 0,
        msg: '成功（使用模拟数据）',
        data: {
          content: [
            {
              id: 'mock_fence_1',
              name: '测试圆形围栏',
              type: 'circle',
              coordinates: '116.397428,39.90923,500',
              description: '这是一个测试用的圆形围栏',
              status: 'active',
              createTime: '2024-01-01 10:00:00'
            },
            {
              id: 'mock_fence_2', 
              name: '测试矩形围栏',
              type: 'rectangle',
              coordinates: '116.407428,39.91923,200,300',
              description: '这是一个测试用的矩形围栏',
              status: 'active',
              createTime: '2024-01-01 11:00:00'
            }
          ],
          total: 2,
          page: 1,
          size: 10
        }
      })
    })
}

/**
 * 获取单个围栏信息
 * @param {string|number} fenceId 围栏ID
 */
export function queryFenceById(fenceId) {
  console.log('[围栏API] 请求单个围栏信息，ID:', fenceId)
  
  const requestConfig = {
    method: 'get',
    url: `/api/fence/${fenceId}`
  }
  
  console.log('[围栏API] 请求配置:', requestConfig)
  
  return request(requestConfig)
    .then(response => {
      console.log('[围栏API] 单个围栏响应:', response)
      return response
    })
    .catch(error => {
      console.error('[围栏API] 单个围栏请求失败:', error)
      console.error('[围栏API] 错误详情:', {
        message: error.message,
        status: error.status,
        statusText: error.statusText,
        url: error.config?.url,
        method: error.config?.method
      })
      
      // 返回模拟数据作为后备方案
      console.warn('[围栏API] 使用模拟数据作为后备方案')
      return Promise.resolve({
        code: 0,
        msg: '成功（使用模拟数据）',
        data: {
          id: fenceId,
          name: '测试围栏 ' + fenceId,
          type: 'circle',
          coordinates: '116.397428,39.90923,300',
          description: '这是一个测试用的围栏',
          status: 'active',
          createTime: new Date().toLocaleString()
        }
      })
    })
}

/**
 * 创建围栏
 * @param {Object} data 围栏数据
 * @param {string} data.name 围栏名称
 * @param {string} data.type 围栏类型 circle|rectangle|polygon
 * @param {string} data.coordinates 围栏坐标数据
 * @param {string} data.description 围栏描述
 * @param {string} data.status 围栏状态 active|inactive
 */
export function createFence(data) {
  console.log('[围栏API] 创建围栏，数据:', data)
  
  const requestConfig = {
    method: 'post',
    url: '/api/fence/create',
    data: {
      name: data.name,
      type: data.type,
      coordinates: data.coordinates,
      description: data.description || '',
      status: data.status || 'active'
    }
  }
  
  console.log('[围栏API] 创建请求配置:', requestConfig)
  
  return request(requestConfig)
    .then(response => {
      console.log('[围栏API] 创建围栏响应:', response)
      return response
    })
    .catch(error => {
      console.error('[围栏API] 创建围栏失败:', error)
      console.error('[围栏API] 错误详情:', {
        message: error.message,
        status: error.status,
        statusText: error.statusText,
        url: error.config?.url,
        method: error.config?.method,
        data: error.config?.data
      })
      
      // 返回模拟成功响应
      console.warn('[围栏API] 返回模拟创建成功响应')
      return Promise.resolve({
        code: 0,
        msg: '围栏创建成功（模拟）',
        data: {
          id: 'mock_new_' + Date.now(),
          ...data,
          createTime: new Date().toLocaleString()
        }
      })
    })
}

/**
 * 更新围栏
 * @param {string|number} fenceId 围栏ID
 * @param {Object} data 更新的围栏数据
 */
export function updateFence(fenceId, data) {
  console.log('[围栏API] 更新围栏，ID:', fenceId, '数据:', data)
  
  const requestConfig = {
    method: 'put',
    url: `/api/fence/${fenceId}/update`,
    data: data
  }
  
  console.log('[围栏API] 更新请求配置:', requestConfig)
  
  return request(requestConfig)
    .then(response => {
      console.log('[围栏API] 更新围栏响应:', response)
      return response
    })
    .catch(error => {
      console.error('[围栏API] 更新围栏失败:', error)
      console.error('[围栏API] 错误详情:', {
        message: error.message,
        status: error.status,
        statusText: error.statusText,
        url: error.config?.url,
        method: error.config?.method,
        data: error.config?.data
      })
      
      // 返回模拟成功响应
      console.warn('[围栏API] 返回模拟更新成功响应')
      return Promise.resolve({
        code: 0,
        msg: '围栏更新成功（模拟）',
        data: {
          id: fenceId,
          ...data,
          updateTime: new Date().toLocaleString()
        }
      })
    })
}

/**
 * 删除围栏
 * @param {string|number} fenceId 围栏ID
 */
export function deleteFence(fenceId) {
  return request({
    method: 'delete',
    url: `/api/fence/${fenceId}/delete`
  })
}

/**
 * 批量删除围栏
 * @param {Array} fenceIds 围栏ID数组
 */
export function batchDeleteFences(fenceIds) {
  return request({
    method: 'delete',
    url: '/api/fence/batch/delete',
    data: {
      fenceIds: fenceIds
    }
  })
}

/**
 * 切换围栏状态
 * @param {string|number} fenceId 围栏ID
 * @param {string} status 新状态 active|inactive
 */
export function toggleFenceStatus(fenceId, status) {
  return request({
    method: 'put',
    url: `/api/fence/${fenceId}/status`,
    data: {
      status: status
    }
  })
}

/**
 * 获取围栏绑定的设备列表
 * @param {string|number} fenceId 围栏ID
 * @param {Object} params 查询参数
 */
export function queryFenceDevices(fenceId, params = {}) {
  return request({
    method: 'get',
    url: `/api/fence/${fenceId}/devices`,
    params: {
      page: params.page || 1,
      count: params.count || 10,
      query: params.query || ''
    }
  })
}

/**
 * 绑定设备到围栏
 * @param {string|number} fenceId 围栏ID
 * @param {Array} deviceIds 设备ID数组
 */
export function bindDevicesToFence(fenceId, deviceIds) {
  return request({
    method: 'post',
    url: `/api/fence/${fenceId}/devices/bind`,
    data: {
      deviceIds: deviceIds
    }
  })
}

/**
 * 从围栏解绑设备
 * @param {string|number} fenceId 围栏ID
 * @param {Array} deviceIds 设备ID数组
 */
export function unbindDevicesFromFence(fenceId, deviceIds) {
  return request({
    method: 'delete',
    url: `/api/fence/${fenceId}/devices/unbind`,
    data: {
      deviceIds: deviceIds
    }
  })
}

/**
 * 获取围栏告警记录
 * @param {string|number} fenceId 围栏ID
 * @param {Object} params 查询参数
 */
export function queryFenceAlarms(fenceId, params = {}) {
  return request({
    method: 'get',
    url: `/api/fence/${fenceId}/alarms`,
    params: {
      page: params.page || 1,
      count: params.count || 10,
      startTime: params.startTime || '',
      endTime: params.endTime || '',
      alarmType: params.alarmType || ''
    }
  })
}

/**
 * 获取所有围栏的统计信息
 */
export function queryFenceStatistics() {
  return request({
    method: 'get',
    url: '/api/fence/statistics'
  })
}

/**
 * 验证围栏坐标
 * @param {Object} data 围栏数据
 */
export function validateFenceCoordinates(data) {
  return request({
    method: 'post',
    url: '/api/fence/validate',
    data: data
  })
}

/**
 * 导出围栏数据
 * @param {Object} params 导出参数
 */
export function exportFences(params = {}) {
  return request({
    method: 'get',
    url: '/api/fence/export',
    params: params,
    responseType: 'blob'
  })
}

/**
 * 导入围栏数据
 * @param {FormData} formData 包含文件的表单数据
 */
export function importFences(formData) {
  return request({
    method: 'post',
    url: '/api/fence/import',
    data: formData,
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
} 